package pers.cnzdy.tutorial.Chapter6_Resource.Section4_Asset;

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import pers.cnzdy.tutorial.R;

public class AssetActivity extends AppCompatActivity {
    private static final String TAG = "Asset";

    private static final String SOUNDS_FOLDER = "my_sounds";
    private static final int MAX_SOUNDS = 10;

    private AssetManager assets;
    private List<Sound> listSounds;
    private SoundPool   soundPool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_asset);

        assets = this.getAssets();
        soundPool = new SoundPool(MAX_SOUNDS, AudioManager.STREAM_MUSIC, 0);
        loadSounds();
    }

    public void playSound(View view)
    {
        Sound sound = listSounds.get(1);
        play(sound);
    }

    public void play(Sound sound) {
        Integer soundId = sound.getSoundId();
        if (soundId == null) {
            Log.d(TAG, "没有声音资源");
            return;
        }
        soundPool.play(soundId, 1.0f, 1.0f, 1, 0, 1.0f);
    }

    public void release() {
        soundPool.release();
    }

    private void loadSounds() {
        String[] soundNames;
        try {
            soundNames = assets.list(SOUNDS_FOLDER);
            Log.i(TAG, "找到 " + soundNames.length + " 声音");
        } catch (IOException ioe) {
            Log.e(TAG, "异常：无法列出资源", ioe);
            return;
        }

        listSounds = new ArrayList<Sound>();
        for (String filename : soundNames) {
            try {
                String assetPath = SOUNDS_FOLDER + "/" + filename;
                Sound sound = new Sound(assetPath);
                load(sound);
                listSounds.add(sound);
            } catch (IOException ioe) {
                Log.e(TAG, "异常：无法加载声音 " + filename, ioe);
            }
        }
    }

    private void load(Sound sound) throws IOException {
        AssetFileDescriptor afd = assets.openFd(sound.getAssetPath());
        int soundId = soundPool.load(afd, 1);
        Log.d(TAG, Integer.toString(soundId));
        sound.setSoundId(soundId);
    }
}